<template>
  <div>

    <searchItem
      @on-search="onSearch"
      @on-clear="onClear"
    />
    <div style="display: flex; align-items: center;" class="row_spacing base">
      <span>{{ $t('now_have') }}<strong>&ensp;{{ totalNum }}&ensp;</strong>{{ $t('strip') }} {{ $t('log') }}</span>
    </div>
    <div class="white">
      <el-row>
        <el-table
          v-loading="listLoading"
          :data="pagedItems"
          :stripe="true"
          element-loading-text="Loading"
          :border="false"
          :header-cell-style="{color:'black'}"
          fit
          highlight-current-row
        >
          <el-table-column :label="$t('time')" align="center" width="160px">
            <template slot-scope="scope">
              {{ scope.row.time }}
            </template>
          </el-table-column>
          <!-- 日志的来源 -->
          <el-table-column :label="$t('source')" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.row.source === 1 ? 'chat' : 'studio' }}
            </template>
          </el-table-column>

          <el-table-column :label="$t('type')" align="center" width="160px">
            <template slot-scope="scope">
              {{ scope.row.app_type | formatType }}
            </template>
          </el-table-column>

          <el-table-column align="left" :label="$t('description')">
            <template slot-scope="scope">
              {{ formatMessage(scope.row.message) }}
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </div>
    <el-pagination
      align="center"
      :total="totalNum"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-count="pageCount"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getLogList } from '@/api/executor'
import searchItem from './LogSearchPanel.vue'

export default {
  components: { searchItem },
  filters: {
    formatType(str) {
      const type_dict = {
        1: 'APP',
        2: 'INFO',
        3: 'WARNNING',
        4: 'ERROR',
        5: 'DEBUG',
        6: 'RELEASE'
      }
      try {
        return type_dict[str]
      } catch (e) {
        console.log('获取日志类型时发生错误', e)
        return 'UNKNOWN'
      }
    }
  },
  props: {
    'appName': {
      type: Array,
      require: true
    },
    'appID': {
      type: String,
      require: true
    }
  },
  data() {
    return {
      /*
      expandedRowKeys: [],
      object: '',
      objectList: [],
      objType: '',
      objTypeList: [
        'app',
        'namespace',
        'node_name',
        'pod'
      ],

      TypeObj: {
        app: [],
        namespace: [],
        node_name: [],
        pod: []
      },
      // 过滤器选择框
      options: [{
        value: '|=',
        label: this.$t('container_detail_log_option1')
      }, {
        value: '!=',
        label: this.$t('container_detail_log_option2')
      }, {
        value: '|~',
        label: this.$t('container_detail_log_option3')
      }, {
        value: '!~',
        label: this.$t('container_detail_log_option4')
      }, {
        value: ' ',
        label: this.$t('container_detail_log_option5')
      }],
      form: {
        date: [],
        filter: '|=',
        input: ''
      },
      labels: {
        label: '',
        value: ''
      },
      flilterList: [],
      labelList: [],
      addFliterID: 0,
      addLabelID: 0,
      flilterContent: '',
      labelContent: '',
      */
      listLoading: true,
      logTable: true,

      logList: [],
      pageCount: 0,
      currentPage: 1,
      pageSize: 15,
      searchForm: {
        key: '',
        start: '',
        end: '',
        type: ''
      }

    }
  },
  computed: {
    // 根据搜索条件筛选数据
    filteredItems() {
      let filtered = this.logList
      // 关键字模糊搜索
      if (this.searchForm.key.trim() !== '') {
        const key = this.searchForm.key.trim().toLowerCase()
        filtered = filtered.filter(item => item.message.toLowerCase().includes(key))
      }
      // 类型搜索
      if (this.searchForm.type && this.searchForm.type !== '0') {
        const key = this.searchForm.type
        filtered = filtered.filter(item => item.app_type === Number(key))
      }
      // 时间范围搜索
      if (this.searchForm.start || this.searchForm.end) {
        filtered = filtered.filter(item => {
          const itemDate = parseInt(new Date(item.time).getTime() / 1000)
          return itemDate >= this.searchForm.start && itemDate <= this.searchForm.end
        })
      }
      return filtered
    },
    pagedItems() {
      const startIndex = (this.currentPage - 1) * this.pageSize
      return this.filteredItems.slice(startIndex, startIndex + this.pageSize)
    },
    // 计算总条数
    totalNum() {
      return this.filteredItems.length
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      const { type } = this.searchForm
      getLogList({
        app_id: this.appID,
        page: this.currentPage,
        pageSize: 99999999,
        app_type: type
      }).then(res => {
        if (res.data.length > 0) {
          this.logList = res.data.slice().reverse()
        }
        this.listLoading = false
      }).catch(() => {
        this.$message.error('获取日志列表失败，请联系管理员')
      })
    },
    /* 将字符串中的第一个\n替换为空格（日志自带的换行），其他正常显示 */
    formatMessage(message) {
      return message.replace(/\n/, ' ').replace(/\n/g, '\\n')
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    onSearch(val) {
      this.currentPage = 1
      this.searchForm = val
    },
    onClear() {
      this.searchForm = {
        key: '',
        start: '',
        end: '',
        type: ''
      }
    },
    // 将字符串：2024-10-12 05:15:01， 加8小时
    timeAddEightHour(dateStr) {
      // 手动解析日期字符串
      const [datePart, timePart] = dateStr.split(' ')
      const [year, month, day] = datePart.split('-').map(Number)
      const [hour, minute, second] = timePart.split(':').map(Number)

      // 创建 Date 对象时，月份需要减 1，因为 JavaScript 的月份是从 0 开始的
      const date = new Date(year, month - 1, day, hour, minute, second)

      // 给时间加上指定的小时数
      date.setHours(date.getHours() + 8)

      // 格式化日期并返回
      const updatedDateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`

      return updatedDateStr
    }
    /*
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
    },
    onsearch() {
      // console.log(this.labelList)

      var btime, etime
      this.listLoading = true
      this.logTable = true
      for (var i = 0; i < this.flilterList.length; i++) {
        this.flilterContent += this.flilterList[i].key + '"' + this.flilterList[i].value + '"'
      }

      this.labelContent = 'app' + '="' + this.projectName + '"'

      if (this.form.date.length === 0 || this.form.date.length === null) {
        btime = Date.now() - 86400000
        etime = Date.now()
        this.form.date = [new Date(btime), new Date(etime)]
      } else {
        btime = this.form.date[0].getTime()
        etime = this.form.date[1].getTime()
      }

      this.logTable = false
      searchRunningLogByType({
        btime: btime,
        etime: etime,
        labelContent: this.labelContent,
        flilterContent: this.flilterContent
      }).then(resp => {
        if (resp.data.logList !== undefined) {
          this.logList = resp.data.logList
          const startTime = new Date(btime)
          const endTime = new Date(etime)
          // eslint-disable-next-line no-unmodified-loop-condition
          while (startTime <= endTime) {
            const year = startTime.getFullYear()
            const month = (startTime.getMonth() + 1).toString().padStart(2, '0')
            const day = startTime.getDate().toString().padStart(2, '0')
            const hours = startTime.getHours().toString().padStart(2, '0')
            // const minutes = startTime.getMinutes().toString().padStart(2, '0')
            const minutes = Math.floor(startTime.getMinutes() / 5) * 5
            const formattedMinutes = minutes.toString().padStart(2, '0')
            const formattedTimestamp = `${year}-${month}-${day} ${hours}:${formattedMinutes}`
            this.timestampCounts.push({
              timestamp: formattedTimestamp,
              value: 0
            })
            startTime.setMinutes(startTime.getMinutes() + 5)
          }
          // 再次遍历日志数据并增加相应时间戳的计数值
          this.logList.forEach(log => {
            const timestamp = log.timestamp
            // const minuteTimestamp = new Date(timestamp).toLocaleString().substr(0, 16)
            const year = new Date(timestamp).getFullYear()
            const month = (new Date(timestamp).getMonth() + 1).toString().padStart(2, '0')
            const day = new Date(timestamp).getDate().toString().padStart(2, '0')
            const hours = new Date(timestamp).getHours().toString().padStart(2, '0')
            // const minutes = new Date(timestamp).getMinutes().toString().padStart(2, '0')
            const minutes = Math.floor(new Date(timestamp).getMinutes() / 5) * 5
            const formattedMinutes = minutes.toString().padStart(2, '0')
            const minuteTimestamp = `${year}-${month}-${day} ${hours}:${formattedMinutes}`
            const entry = this.timestampCounts.find(entry => entry.timestamp === minuteTimestamp)
            if (entry) {
              entry.value++
            }
          })
          this.renderChart()
          this.totalNum = this.logList.length
          this.pageCount = parseInt(this.totalNum / this.pageSize)
          if (this.totalNum % this.pageSize > 0) {
            this.pageCount = this.pageCount + 1
          }

          this.listLoading = false
          Message({
            message: this.$t('query_success_tips'),
            type: 'success'
          })
        } else {
          this.logTable = true
          this.logList = []
          this.renderChart()
          Message({
            message: this.$t('container_log_queryFail'),
            type: 'warning'
          })
        }
      })

      this.timestampCounts = []
      this.flilterContent = ''
      this.labelContent = ''
      this.handleCurrentChange(1)
    },
    changeSelect() {
      this.object = ''
      for (const k in this.objTypeList) {
        if (this.objType === this.objTypeList[k]) {
          this.objectList = this.TypeObj[this.objType]
        }
      }
    },
    changeTime(val) {
      if (new Date(val[1]) - new Date(val[0]) > 1 * 24 * 60 * 60 * 1000 * 30) {
        Message({
          message: this.$t('data_range_max_30'),
          type: 'warning'
        })
        this.form.date[0] = ''
        this.form.date[1] = ''
      }
    },
    addFilterTag(key, value) {
      this.flilterList.push({ id: this.addFliterID, key: key, value: value })
      this.form.input = ''
      this.addFliterID += 1
    },

    deleteTag(id) {
      // 在 flilterList 中查找要删除的元素的索引
      const indexTagToDelete = this.flilterList.findIndex(item => item.id === id)
      if (indexTagToDelete !== -1) {
        // 使用 splice 方法删除该元素
        this.flilterList.splice(indexTagToDelete, 1)
        Message({
          message: 'FilterTag with ID ' + id + ' deleted.',
          type: 'success'
        })
      } else {
        console.error('Element with ID ' + id + ' not found.')
        Message({
          message: 'FilterTag with ID ' + id + ' not found.',
          type: 'warning'
        })
      }
    },

    renderChart() {
      const chartData = {
        data: this.timestampCounts
        // data的格式如下
        // data: [
        //   {
        //     timestamp: '2023-10-01 00:00:00',
        //     value: 10
        //   },
        //   {
        //     timestamp: '2023-10-01 01:00:00',
        //     value: 20
        //   },
        //   {
        //     timestamp: '2023-10-01 02:00:00',
        //     value: 16
        //   }
        // ]
      }

      // 初始化ECharts实例
      const chart = echarts.init(document.getElementById('bar-chart'))

      // 提取数据
      const timestamps = chartData.data.map(item => item.timestamp)
      const values = chartData.data.map(item => item.value)

      const maxValue = Math.max(...values)
      let intervalNum = 0

      if (maxValue > 20) {
        intervalNum = (Math.floor(maxValue / 10) * 10) / 4
      } else {
        intervalNum = 5
      }

      // 配置项
      const option = {
        backgroundColor: 'white',
        grid: {
          left: 55,
          right: 55,
          top: 30
          // bottom: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10],
          formatter: function(params) {
            let res = `<table style="width: 100%;"><tr><td colspan="2"><B>${params[0].name}</B></td></tr>`
            const maxLength = Math.max(...params.map((p) => p.seriesName.length))
            for (let i = 0, length = params.length; i < length; i++) {
              const color = params[i].color
              const label = params[i].seriesName.padEnd(maxLength, ' ')
              const value = params[i].value
              res +=
                '<tr>' +
                `<td><span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:${color};"></span></td>` +
                `<td style="text-align: left; padding-left: 8px">${label}:</td>` +
                `<td style="text-align: right; padding-left: 8px"><B>${value}</B></td>` +
                '</tr>'
            }
            res += '</table>'
            return res
          }
        },
        // 可拉伸横轴
        dataZoom: [
          {
            type: 'slider',
            show: true,
            start: 80,
            end: 100,
            handleSize: '100%'
          },
          {
            type: 'inside',
            start: 85,
            end: 100
          }
        ],
        xAxis: {
          data: timestamps,
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          // name: '数量',
          min: 0,
          max: Math.max(...values) + 10, // 设置纵轴的最大值，可以根据数据调整
          position: 'left',
          axisLabel: {
            formatter: '{value}'
          },
          // interval: (Math.floor(Math.max(...values) / 10) * 10) / 4
          interval: intervalNum
        },
        series: [
          {
            name: '日志数量',
            barWidth: 2,
            itemStyle: {
              normal: {
                color: '#409eff',
                lineStyle: {
                  color: '#ff0000',
                  width: 1
                }
              }
            },
            smooth: true,
            type: 'bar',
            yAxisIndex: 0,
            data: values,
            animationDuration: 2800,
            animationEasing: 'cubicInOut'
          }
        ]
      }
      // 使用配置项绘制图表
      chart.setOption(option)
    },

    exportToCsv() {
      // 将数据转换为工作表
      const columnOrder = ['id', 'timestamp', 'content', 'stream', 'app', 'container', 'pod', 'node_name', 'component', 'namespace', 'job', 'filename', 'instance']
      const ws = XLSX.utils.json_to_sheet(this.logList, { header: columnOrder })
      // 创建新的工作簿并添加工作表
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      // 导出CSV
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
      const day = currentDate.getDate().toString().padStart(2, '0')
      const hours = currentDate.getHours().toString().padStart(2, '0')
      const minutes = currentDate.getMinutes().toString().padStart(2, '0')
      const seconds = currentDate.getSeconds().toString().padStart(2, '0')
      const localFormattedDate = `${year}_${month}_${day}_${hours}_${minutes}_${seconds}`
      const filename = `log_output_${localFormattedDate}.csv`
      XLSX.writeFile(wb, filename)
    }
     */
  }
}
</script>

<style>
.el-tag {
  margin-right: 5px;
  font-size: 14px
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  margin-left: 50px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  width: 90%;
}
.el-pagination__rightwrapper{
  display: none
}
</style>
